/************************************************************************
  * Copyright(c) 2023 Levetop Semiconductor Co.,Led. All rights reserved.
  * @file     uart_update.c
  * @author   UartTFT Application Team
  * @version  V0.0.1
  * @date     2023-01-01
  * @brief     
 *************************************************************************/
 
/************************************************************************
	2023.03.02	-- add the write address limit range of the mcu
 *************************************************************************/
#include "uart_update.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "sys.h"
#include "eflash_drv.h"
#include "ssi_drv.h"
#include "reset_drv.h"
#include "bsp.h"
#include "wav_dac.h"


UART_UPDATE_ U_UPDATE;

/*analyse*/
uint8_t U_UpdateCMDanalyse(uint8_t cmd, uint8_t *buf)
{
	uint16_t rxCrc, mcuCrc;
	uint16_t i, len = 0;
	uint8_t rebuf[260];

	uint32_t u_addr = 0, u_len = 0;
	uint32_t total_crc, file_crc;
	uint8_t u_index = 0, u_crc[4] = {0};
	uint16_t pos, ll;

	rxCrc = buf[gUsartRx.Count - 1];
	rxCrc = (rxCrc << 8) + buf[gUsartRx.Count - 2];
	mcuCrc = CRC16(&buf[1], gUsartRx.Count - 3);

	if (cmd == 0x61) // mcu flash ----------------------------------------------
	{
		len = buf[0];
		u_index = buf[2];
		u_addr = ((buf[3] << 24) | (buf[4] << 16) | (buf[5] << 8) | buf[6]); // Start address of each frame
		// printf("mcu u_addr=0x%x\n",u_addr);
		
		// 1.Burn and write MCU Flash transmission data package��------------------------------------------------
		if ((u_index & 0xF0) == 0x00)
		{
			if (u_index == 0) // Unpacked first frame data
			{
				U_UPDATE.dsum = 0;
				U_UPDATE.addr = u_addr; // Start address of each package
			}

			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			//					else if(len<=8)   U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				pos = 240 * (u_index & 0xF); // Calculate the location of data according to the unpacking id
				ll = len - 8;				 // Data length

				if ((pos + ll) > 2048)
					pos = 0;

				for (i = 0; i < ll; i++)
					U_UPDATE.dbuf[pos + i] = buf[7 + i];
				U_UPDATE.dsum = pos + ll;
			}

			if (U_UPDATE.dsum >= 2048) // Prevent data length from exceeding buffer
			{
				U_UPDATE.dsum = 0; // error
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			memcpy(&rebuf[6], &buf[3], 4);
			LT_SendData_CRC_Frame(rebuf, 7);
		}
		 // 2.Burn and write MCU Flash end data package��----------------
		else if (u_index & 0x80)
		{
			if ((u_index & 0xF) == 0)
			{
				U_UPDATE.dsum = 0;
				U_UPDATE.addr = u_addr; // Start address of each package
			}

			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			//					else if(len<=8)   U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				pos = 240 * (u_index & 0xF); // Calculate the location of data according to the unpacking id
				ll = len - 8;				 // Data length

				if ((pos + ll) > 2048)
					pos = 0;

				for (i = 0; i < ll; i++)
					U_UPDATE.dbuf[pos + i] = buf[7 + i];
				U_UPDATE.dsum = pos + ll;
			}
			// printf("u_index=%d,U_UPDATE.dsum=%d %d\n",u_index,U_UPDATE.dsum,(len-8));
			if (U_UPDATE.msg == U_MSG_OK)
			{
				U_McuFlash_Update(U_UPDATE.addr, U_UPDATE.dsum);
				U_UPDATE.dsum = 0; // clear
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			memcpy(&rebuf[6], &buf[3], 4);
			LT_SendData_CRC_Frame(rebuf, 7);
		}
		// 3.Data verification and return crc---------------------
		else if (u_index == 0x40) 
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			// else if(len!=12)  U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			total_crc = 0x0;
			if (U_UPDATE.msg == U_MSG_OK)
			{
				u_addr = ((buf[3] << 24) | (buf[4] << 16) | (buf[5] << 8) | buf[6]);
				u_len = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]);
				file_crc = ((buf[11] << 24) | (buf[12] << 16) | (buf[13] << 8) | buf[14]);

				total_crc = U_McuFlash_ReadDataCrc(u_addr, u_len);
				// printf("u_addr = 0x%x, u_len = %d\n",u_addr,u_len);
				// printf("mcu total_crc = 0x%x\n",total_crc);
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			rebuf[6] = total_crc >> 24;
			rebuf[7] = total_crc >> 16;
			rebuf[8] = total_crc >> 8;
			rebuf[9] = total_crc & 0xFF;
			LT_SendData_CRC_Frame(rebuf, 7);
		}
		// 4.update command: MCU moves buffered data to the operation area--------------------
		else if (u_index == 0x20) 
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			else if (len != 12)
				U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				u_addr = ((buf[3] << 24) | (buf[4] << 16) | (buf[5] << 8) | buf[6]);
				u_len = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]);
				file_crc = ((buf[11] << 24) | (buf[12] << 16) | (buf[13] << 8) | buf[14]);
				
				U_UPDATE.msg = U_McuFlash_DataToWorkspace(u_addr, u_len, file_crc);
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			memset(&rebuf[6], 0, 4);
			LT_SendData_CRC_Frame(rebuf, 7);
		}
		// 5.Query the current MCU version --------------------
		else if (u_index == 0x50) 
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			else if (len != 4)
				U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				U_McuFlash_GetVersion(&rebuf[6]);

				rebuf[3] = cmd;
				rebuf[4] = u_index;		 // index
				rebuf[5] = U_UPDATE.msg; // Msg
				LT_SendData_CRC_Frame(rebuf, 15);
			}
		}
		//6.Jump to factory mcu --------------------
		else if (u_index == 0x51)
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			else if (len != 4)
				U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				U_McuFlash_Factory();
			}
		}
		// 7.Jump to update mcu --------------------
		else if (u_index == 0x52)
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			else if (len != 4)
				U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				U_McuFlash_Bsp();
			}
		}
		// 8.Modify MCU code update area data--------------------
		else if (u_index == 0x53)
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			else if (len != 18)
				U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				U_UPDATE.msg = U_McuFlash_InfoChange(&buf[3], len - 5);
			}
			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			LT_SendData_CRC_Frame(rebuf, 3);
		}
		// 9.Clear MCU code update area data --------------------
		else if (u_index == 0x54) 
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			else if (len != 4)
				U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				U_UPDATE.msg = U_McuFlash_InfoClear();
			}
			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			LT_SendData_CRC_Frame(rebuf, 3);
		}
	}
	else if (cmd == 0x62) // 10.Read MCU Flash data----------------
	{
		len = buf[0];

		if (rxCrc != mcuCrc)
			U_UPDATE.msg = U_MSG_CRC_ERROR;
		else if (len != 8)
			U_UPDATE.msg = U_MSG_FORMAT_ERROR;
		else
			U_UPDATE.msg = U_MSG_OK;

		if (U_UPDATE.msg == U_MSG_OK)
		{
			u_addr = ((buf[2] << 24) | (buf[3] << 16) | (buf[4] << 8) | buf[5]);
			u_len = buf[6];

			U_UPDATE.msg = U_McuFlash_ReadData(U_UPDATE.dbuf, u_addr, u_len);

			if (U_UPDATE.msg != U_MSG_OK)
				u_len = 0;
		}

		rebuf[3] = cmd;
		rebuf[4] = U_UPDATE.msg; // Msg
		memcpy(&rebuf[5], U_UPDATE.dbuf, u_len);
		LT_SendData_CRC_Frame(rebuf, u_len + 2);
	}
	else if (cmd == 0x65) // SPI Flash-------------------------------------------
	{
		len = buf[0];
		u_index = buf[2];
		u_addr = ((buf[3] << 24) | (buf[4] << 16) | (buf[5] << 8) | buf[6]);

		// 11.Burn and write SPI Flash transmission data package -----------------------------------------------------------------------------------------------
		if ((u_index & 0xF0) == 0x00)
		{
			if (u_index == 0)
			{
				U_UPDATE.dsum = 0;
				U_UPDATE.addr = u_addr; // Start address of each package
			}

			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			//					else if(len<=8)   U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				pos = 240 * (u_index & 0xF);
				ll = len - 8;
				if ((pos + ll) > 2048)
					pos = 0;

				for (i = 0; i < ll; i++)
					U_UPDATE.dbuf[pos + i] = buf[7 + i];
				U_UPDATE.dsum = pos + ll;
				// printf("spi pos=%d %d\n",pos,U_UPDATE.dsum);
			}

			if (U_UPDATE.dsum >= 2048)
			{
				U_UPDATE.dsum = 0; // error
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			memcpy(&rebuf[6], &buf[3], 4);
			LT_SendData_CRC_Frame(rebuf, 7);
		}
		// 12.Burn SPI Flash end packet:-----------------------------------------------------------------------------------------------
		else if (u_index & 0x80)
		{
			if ((u_index & 0xF) == 0)
			{
				U_UPDATE.dsum = 0;
				U_UPDATE.addr = u_addr; // Start address of each package
			}

			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			else if (len <= 8)
				U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				pos = 240 * (u_index & 0xF);
				ll = len - 8;
				if ((pos + ll) > 2048)
					pos = 0;

				for (i = 0; i < ll; i++)
					U_UPDATE.dbuf[pos + i] = buf[7 + i];
				U_UPDATE.dsum = pos + ll;
				// printf("spi pos=%d %d\n",pos,U_UPDATE.dsum);
			}

			if (U_UPDATE.msg == U_MSG_OK)
			{
				U_SpiFlash_Update(U_UPDATE.addr, U_UPDATE.dsum);
				U_UPDATE.dsum = 0; // clear
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			memcpy(&rebuf[6], u_crc, 4);
			LT_SendData_CRC_Frame(rebuf, 7);
		}
		// 13.data verification and return CRC------------------------------------------------------------------
		else if (u_index == 0x40)
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			// else if(len!=12)  U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			total_crc = 0x0;
			if (U_UPDATE.msg == U_MSG_OK)
			{
				u_addr = ((buf[3] << 24) | (buf[4] << 16) | (buf[5] << 8) | buf[6]);
				u_len = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]);
				file_crc = ((buf[11] << 24) | (buf[12] << 16) | (buf[13] << 8) | buf[14]);
				//                        printf("u_addr = 0x%x, u_len = %d\n",u_addr,u_len);
				total_crc = U_SpiFlash_ReadDataCrc(u_addr, u_len);
				//                        printf("mcu total_crc = 0x%x\n",total_crc);
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			// memcpy(&rebuf[6], u_crc, 4);
			rebuf[6] = total_crc >> 24;
			rebuf[7] = total_crc >> 16;
			rebuf[8] = total_crc >> 8;
			rebuf[9] = total_crc & 0xFF;
			LT_SendData_CRC_Frame(rebuf, 7);
		}
		// 14.update instruction: SPI Flash moves buffered data to the running area--------------------------------------------------
		else if (u_index == 0x20)
		{
			if (rxCrc != mcuCrc)
				U_UPDATE.msg = U_MSG_CRC_ERROR;
			// else if(len!=12)  U_UPDATE.msg = U_MSG_FORMAT_ERROR;
			else
				U_UPDATE.msg = U_MSG_OK;

			if (U_UPDATE.msg == U_MSG_OK)
			{
				u_addr = ((buf[3] << 24) | (buf[4] << 16) | (buf[5] << 8) | buf[6]);
				u_len = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]);
				file_crc = ((buf[11] << 24) | (buf[12] << 16) | (buf[13] << 8) | buf[14]);
				
				total_crc = U_SpiFlash_DataToWorkspace(u_addr, u_len, file_crc);
			}

			rebuf[3] = cmd;
			rebuf[4] = u_index;		 // index
			rebuf[5] = U_UPDATE.msg; // Msg
			rebuf[6] = total_crc >> 24;
			rebuf[7] = total_crc >> 16;
			rebuf[8] = total_crc >> 8;
			rebuf[9] = total_crc & 0xFF;
			LT_SendData_CRC_Frame(rebuf, 7);

			Set_POR_Reset(); // mcu reset
		}
	}
	// 15.Read SPI Flash data-----------------------------------------------------------------------------------------------
	else if (cmd == 0x66)
	{
		len = buf[0];

		if (rxCrc != mcuCrc)
			U_UPDATE.msg = U_MSG_CRC_ERROR;
		else if (len != 8)
			U_UPDATE.msg = U_MSG_FORMAT_ERROR;
		else
			U_UPDATE.msg = U_MSG_OK;

		if (U_UPDATE.msg == U_MSG_OK)
		{
			u_addr = ((buf[2] << 24) | (buf[3] << 16) | (buf[4] << 8) | buf[5]);
			u_len = buf[6];

			U_UPDATE.msg = U_SpiFlash_ReadData(U_UPDATE.dbuf, u_addr, u_len);

			if (U_UPDATE.msg != U_MSG_OK)
				u_len = 0;
		}

		rebuf[3] = cmd;
		rebuf[4] = U_UPDATE.msg; // Msg
		memcpy(&rebuf[5], U_UPDATE.dbuf, u_len);
		LT_SendData_CRC_Frame(rebuf, u_len + 2);
	}
}

const uint32_t CRC32_Table[256] = {
	0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
	0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
	0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
	0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
	0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
	0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
	0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
	0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
	0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
	0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
	0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
	0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
	0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
	0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
	0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
	0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
	0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
	0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
	0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
	0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
	0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
	0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
	0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
	0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
	0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
	0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
	0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
	0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
	0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
	0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
	0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
	0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
	0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
	0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
	0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
	0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
	0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
	0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
	0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
	0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
	0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
	0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
	0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
	0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
	0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
	0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
	0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
	0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
	0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
	0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
	0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
	0x2D02EF8D};

uint32_t GetCrc32(uint8_t *InStr, uint32_t len)
{
	//Generate query table of CRC16
	uint32_t i;
	uint32_t Crc;
	uint8_t *pch;

	// Start to calculate the CRC16 check value
	Crc = 0x0;
	pch = InStr;

	for (i = 0; i < len; i++)
	{
		Crc = (Crc >> 8) ^ CRC32_Table[(Crc & 0xFF) ^ (*pch)];
		pch++;
	}
	// PrintfHex(Crc);

	return Crc;
}

/* MCU */
uint8_t U_McuFlash_Update(uint32_t u_addr, uint16_t u_len)
{
	uint8_t reVal;
	uint16_t efmLen;
	uint32_t efmAddr;
	uint32_t i, crc32;

	efmAddr = U_UPDATE.addr + U_MCUFLASH_UPDATE_ADDR; //  + U_MCUFLASH_UPDATE_ADDR
	/* if (efmAddr > 0x0807E000)   size = 1024 * 236 */
	if (efmAddr < U_MCUFLASH_UPDATE_ADDR || efmAddr >= (U_MCUFLASH_UPDATE_ADDR + 1024 * 236))
		return U_MSG_CARRY_FAILURE; // over than 1024*504

	efmLen = U_UPDATE.dsum;

	EFLASH_Init(g_sys_clk / 1000);
	EFLASH_SetWritePermission();
	reVal = EFLASH_Write(efmAddr, &U_UPDATE.dbuf[0], efmLen);
	EFLASH_ClrWritePermission();

	return U_MSG_OK;
}

uint32_t U_McuFlash_ReadDataCrc(uint32_t u_addr, uint32_t u_len)
{
	uint32_t cCRC = 0x0;
	uint32_t enterAddr;
	int32_t i, tLen = u_len;
	uint8_t rdByte;

	enterAddr = u_addr + U_MCUFLASH_UPDATE_ADDR; // + U_MCUFLASH_UPDATE_ADDR
	// calculate Flash CRC32 Value
	for (i = 0; i < tLen; i++)
	{

		rdByte = EFLASH_ByteRead(enterAddr + i);
		cCRC = (cCRC >> 8) ^ CRC32_Table[(cCRC & 0xFF) ^ (rdByte)];
	}

	return cCRC;
}

uint32_t U_McuFlash_DataToWorkspace(uint32_t u_addr, uint32_t u_len, uint32_t u_crc)
{
	//		APP(APP_ADDR);

	return U_MSG_OK;
}

uint8_t U_McuFlash_ReadData(uint8_t *buf, uint16_t u_addr, uint16_t u_len)
{
	return U_MSG_OK;
}

uint8_t U_McuFlash_GetVersion(uint8_t *buf)
{
	//	uint8_t* str = (uint8_t*)&U_MCUFLASH_VERSION;

	strcpy((char *)buf, U_MCUFLASH_VERSION);
}

uint8_t U_McuFlash_Factory(void)
{
	APP(U_MCUFLASH_FACTORY_ADDR); // Jump to
	return U_MSG_OK;
}

uint8_t U_McuFlash_Bsp(void)
{
	APP(U_MCUFLASH_UPDATE_ADDR); // Jump to
	return U_MSG_OK;
}

uint8_t U_McuFlash_InfoChange(uint8_t *buf, uint16_t u_len)
{
	uint8_t reVal;
	uint32_t crc, crc_info;

	if (u_len > 256)
		return U_MSG_CARRY_FAILURE;

	crc = GetCrc32(&buf[2], 8);
	crc_info = ((buf[10] << 24) | (buf[11] << 16) | (buf[12] << 8) | buf[13]);
	if (crc_info != crc)
		return U_MSG_CARRY_FAILURE;

	EFLASH_Init(g_sys_clk / 1000);
	EFLASH_SetWritePermission();
	reVal = EFLASH_Write(U_MCUFLASH_INFOADDR, buf, u_len);
	EFLASH_ClrWritePermission();
	// if(reVal != TRUE)   return U_MSG_CARRY_FAILURE;

	return U_MSG_OK;

#if 0
	uint8_t BUF[14];
	uint32_t crc,msg=0;
	uint32_t bsp_crc=0x14842b2f, bsp_len=187284 ;
	//uint32_t bsp_crc=0, bsp_len=0 ;

	BUF[0] = 0X5A;
	BUF[1] = 0XA5;
	
	BUF[2] = (bsp_crc>>24)&0xFF;
	BUF[3] = (bsp_crc>>16)&0xFF;
	BUF[4] = (bsp_crc>>8)&0xFF;
	BUF[5] = bsp_crc&0xFF;

	BUF[6] = (bsp_len>>24)&0xFF;
	BUF[7] = (bsp_len>>16)&0xFF;
	BUF[8] = (bsp_len>>8)&0xFF;
	BUF[9] = bsp_len&0xFF;
	
	crc = GetCrc32(&BUF[2],8);
	BUF[10] = (crc>>24)&0xFF;
	BUF[11] = (crc>>16)&0xFF;
	BUF[12] = (crc>>8)&0xFF;
	BUF[13] = crc&0xFF;

	msg = U_McuFlash_InfoChange(BUF,14);
//	printf("U_McuFlash_InfoChange   crc=0x%x  msg=%d \r\n",crc,msg);
#endif
}

uint8_t U_McuFlash_InfoClear(void)
{

	EFLASH_Init(g_sys_clk / 1000);
	EFLASH_SetWritePermission();
	EFLASH_PageErase(U_MCUFLASH_INFOADDR); // erase 256Bytes
	EFLASH_ClrWritePermission();
	
	//debug
//	uint8_t buf[2];
//	for (uint8_t i = 0; i < 2; i++)
//		buf[i] = EFLASH_ByteRead(U_MCUFLASH_INFOADDR + i);
//	printf("U_McuFlash_Factory  after buf[i] =0x%x 0x%x  \r\n",buf[0],buf[1]);
}

/* SPI Flash  */
uint8_t U_SpiFlash_Update(uint32_t u_addr, uint16_t u_len) // Flash_Type=1;
{
	// printf("spi u_addr=0x%x %d\n",U_UPDATE.addr,U_UPDATE.dsum);
	uint32_t i, j, l0, l1;
	uint32_t wrAddr;
	uint8_t *pWrBuf;

	// printf("spi u_addr=0x%x %d, crc=0x%x\n",U_UPDATE.addr,U_UPDATE.dsum,GetCrc32(&U_UPDATE.dbuf[0],U_UPDATE.dsum));

	SSI1_STD_Init(SSI1);

	wrAddr = U_UPDATE.addr + U_SPIFLASHADDR; // 0x800000:1024*1024*8(Mbytes),��16Mbytes��Flash�м俪ʼ

	// printf("(wrAddr (1024*64))= %d\n",(wrAddr%(1024*64)));

	if (Flash_Type != 2)
	{
		if ((wrAddr % (1024 * 4)) == 0)
		{
			W25QXX_SectorErase4K(wrAddr);
		}

		l0 = U_UPDATE.dsum / 256;
		l1 = U_UPDATE.dsum % 256;
		if (l1)
			l0++;

		for (i = 0; i < l0; i++)
		{
			pWrBuf = &(U_UPDATE.dbuf[i * 256]);
			W25QXX_STD_Write_NoCheck(pWrBuf, wrAddr + i * 256, 256);
		}
	}
	else
	{
		if ((wrAddr % (1024 * 128)) == 0)
		{
			LT_W25N01GV_BlockErase128KB(wrAddr);
		}

		//			l0 = U_UPDATE.dsum/(1024*2);
		//			l1 = U_UPDATE.dsum%(1024*2);
		//			if(l1) l0++;
		//
		//			for(i=0;i<l0;i++)
		//			{
		//					pWrBuf = &(U_UPDATE.dbuf[i*256]);
		LT_W25N01GV_STD_Write_NoCheck_DMA(pWrBuf, wrAddr, (1024 * 2));
		//			}
	}

	return U_MSG_OK;
}

uint32_t U_SpiFlash_ReadDataCrc(uint32_t u_addr, uint32_t u_len)
{
	uint8_t inBuf[64];
	uint8_t rdByte;
	uint32_t i = 0, j = 0, k, l0, l1;
	uint32_t newCRC;
	// UN_u32Data tUN;
	uint32_t len, addr, addrbyteNum;

	volatile uint8_t temp;
	int32_t txnum, rxnum;

	addr = u_addr + U_SPIFLASHADDR; // 0x800000:1024*1024*8(Mbytes),��16Mbytes��Flash�м俪ʼ

	// calculate Flash CRC32 Value
	newCRC = 0x0;
	l0 = u_len / 256;
	l1 = u_len % 256;

	// calculate Flash CRC32 Value
	newCRC = 0x0;
	for (i = 0; i < l0; i++)
	{
		LT_ReadFlash(U_UPDATE.dbuf, addr + i * 256, 256);
		for (j = 0; j < 256; j++)
		{
			rdByte = U_UPDATE.dbuf[j];
			newCRC = (newCRC >> 8) ^ CRC32_Table[(newCRC & 0xFF) ^ (rdByte)];
		}
	}

	if (l1 > 0)
	{
		LT_ReadFlash(U_UPDATE.dbuf, addr + l0 * 256, 256);
		for (j = 0; j < l1; j++)
		{
			rdByte = U_UPDATE.dbuf[j];
			newCRC = (newCRC >> 8) ^ CRC32_Table[(newCRC & 0xFF) ^ (rdByte)];
		}
	}

	return newCRC;
}

uint32_t U_SpiFlash_DataToWorkspace(uint32_t u_addr, uint32_t u_len, uint32_t u_crc)
{
	uint32_t i, j, l0, l1;
	uint32_t rdAddr, wrAddr;
	uint32_t tCrc;
	uint8_t *pWrBuf;

	// less than half of spiflash size
	if (u_len <= U_SPIFLASHADDR)
	{
		if (Flash_Type != 2)
		{
			l0 = u_len / (1024 * 64);
			l1 = u_len % (1024 * 64);
			if (l1 > 0)
				l0++;

			//printf("Erase spi flash\n");
			SSI1_STD_Init(SSI1);

			for (i = 0; i < l0; i++)
			{
				wrAddr = i * 1024 * 64; // 64K erase
				W25QXX_BlockErase64KB(wrAddr);
			}

			// Calculate the number of pages to copy
			l0 = u_len / 256;
			l1 = u_len % 256;
			if (l1 > 0)
				l0++;

			U_SpiFlashDisableScreen(); // disable screen

			//        printf("Wrtie spi flash\n");
			for (i = 0; i < l0; i++)
			{
				rdAddr = U_SPIFLASHADDR + i * 256;
				NorFlash_Read(U_UPDATE.dbuf, rdAddr, 256);

				wrAddr = i * 256; // write 256 bytes 

				SSI1_STD_Init(SSI1);
				W25QXX_STD_Write_NoCheck(U_UPDATE.dbuf, wrAddr, 256);
			}
			// calculate CRC
			tCrc = U_SpiFlash_ReadDataCrc(0x0, u_len);
			//printf("Crc: 0x%x 0x%x\n",tCrc,u_crc);

			return tCrc;
		}
		else
		{
			l0 = u_len / (1024 * 128);
			l1 = u_len % (1024 * 128);
			if (l1 > 0)
				l0++;

			//printf("Erase spi flash\n");

			SSI1_STD_Init(SSI1);

			for (i = 0; i < l0; i++)
			{
				wrAddr = i * 1024 * 128; // 128K erase
				LT_W25N01GV_BlockErase128KB(wrAddr);
			}

			// Calculate the number of pages to copy
			l0 = u_len / (1024 * 2);
			l1 = u_len % (1024 * 2);
			if (l1 > 0)
				l0++;

			U_SpiFlashDisableScreen(); // disable screen

			//        printf("Wrtie spi flash\n");
			for (i = 0; i < l0; i++)
			{
				rdAddr = U_SPIFLASHADDR + i * 1024 * 2;
				LT_ReadFlash(U_UPDATE.dbuf, rdAddr, 1024 * 2);

				wrAddr = i * 1024 * 2; // write 2K

				SSI1_STD_Init(SSI1);
				LT_W25N01GV_STD_Write_NoCheck_DMA(U_UPDATE.dbuf, wrAddr, 1024 * 2);
			}
			// calculate CRC
			tCrc = U_SpiFlash_ReadDataCrc(0x0, u_len);
			//        printf("Crc: 0x%x 0x%x\n",tCrc,u_crc);

			return tCrc;
		}
	}

	return 0x0;
}

uint8_t U_SpiFlash_ReadData(uint8_t *buf, uint16_t u_addr, uint16_t u_len)
{
}

uint8_t U_SpiFlashDisableScreen(void)
{
	U_UPDATE.updateflag = 1; // uart_update

	/*Close interrupt*/


	/*clear flag*/
	Basci_count = 0;
	Basci_flag = 0;
	//	Ges_sc_flag = 0;
	Adj_count = 0;
	Adj_flag = 0;

	Slide_count = 0;
	Slide_flag = 0;

	Dio_count = 0;
	Dio_flag = 0;
	DioKb_flag = 0;
	Aio_count = 0;
	AioKb_flag = 0;
	Aio_flag = 0;
	GBKio_count = 0;
	GBKioKb_flag = 0;
	GBKio_flag = 0;
	Kb_count = 0;
	Kb_flag = 0;

	sldmenu_count = 0;
	sldmenu_flag = 0;

	VarKey_count = 0;
	VarKey_flag = 0;

	Pop_up_count = 0;
	Pop_up_flag = 0;
	button_Press_flag = 0;
	
	data_D_num = 0;
	//	memset(data_D_w,0,50);
	memset(data_D_w, 0, sizeof(data_D_w));
	
	pdata_D_num = 0;
	
	Gif_num = 0;
	RTC_num = 0;
	Clock_num = 0;	
	Scroll_num = 0;	  
	Gesture_flag = 0;
	RingSld_count = 0; 
	curve_num = 0;	  
	gEncoderFlag = 0; 

	Saving_counting_parameters(); 
	
#if (UARTBUS_OPTION == 2)
	if (gUsartTx.Mode == 0x02)
		tx_repeat_flag = 0;
#endif
	if (gWavFlag == 1 || gWavType == 1)
	{
		gWavType = 0;
		close_wav_dac();
	}

	RTC_Get();
	var[(VAR_TIME + 0) * 2 + 1] = calendar.w_year - 2000;
	var[(VAR_TIME + 1) * 2 + 1] = calendar.w_month;
	var[(VAR_TIME + 2) * 2 + 1] = calendar.w_date;
	var[(VAR_TIME + 3) * 2 + 1] = calendar.hour;
	var[(VAR_TIME + 4) * 2 + 1] = calendar.min;
	var[(VAR_TIME + 5) * 2 + 1] = calendar.sec;
	var[VAR_TIMESET * 2 + 1] = calendar.week;
}

uint8_t U_McuFlash_CheckBsp(void)
{
	uint8_t i, j, buf[14] = {0};
	uint32_t bsp_crc, bsp_len, info_crc, crc;

	U_UPDATE.updateflag = 0; // uart_update

	for (j = 0; j < 3; j++)
	{
		for (i = 0; i < 14; i++)
			buf[i] = EFLASH_ByteRead(U_MCUFLASH_INFOADDR + i);

		if (buf[0] == 0x5A && buf[1] == 0xA5) // frame header
		{
			bsp_crc = ((buf[2] << 24) | (buf[3] << 16) | (buf[4] << 8) | buf[5]);
			bsp_len = ((buf[6] << 24) | (buf[7] << 16) | (buf[8] << 8) | buf[9]);
			info_crc = ((buf[10] << 24) | (buf[11] << 16) | (buf[12] << 8) | buf[13]);

			if (bsp_len <= 1024 * 236)
			{
				crc = GetCrc32(&buf[2], 8);

				if (crc == info_crc)
				{
					crc = U_McuFlash_ReadDataCrc(0, bsp_len); // read crc, addr + U_MCUFLASH_UPDATE_ADDR

					if (crc == bsp_crc)
					{
						APP(U_MCUFLASH_UPDATE_ADDR); // jump to bsp
					}
				}
			}
		}
	}
}

//----------------------------------------------------------------------------------
#include "cache_drv.h"
#include "common.h"

typedef void (*iapfun)(void); // Define parameters of a function type.
iapfun jump2app;

void APP(uint32_t appxaddr)
{
	//	if(((*(vu32*)appxaddr)&0x2FFC2000)==0x20000000)
	//	{
	jump2app = (iapfun) * (vu32 *)(appxaddr + 4);

	MSR_MSP(*(vu32 *)appxaddr);

	DCACHE_Init(cacheOff, cacheOff, cacheOff, cacheOff);
	ICACHE_Init(cacheOff, cacheOff, cacheOff, cacheOff);

	// gUSBC_ComReg->INTRUSBE &= ~(USB_INTERRUPT_DISCON | USB_INTERRUPT_CONNECT| USB_INTERRUPT_RESET);  //close USB interrupt
	Disable_Interrupts;
	jump2app();
	//	}
}
